import defineVersionedConfig from 'vitepress-versioning-plugin'
import { loadLocales, processExistingEntries } from './i18n';
import { transformItems, transformPageData } from './transform';
import { latest_version } from "./version"
import { tabsMarkdownPlugin } from 'vitepress-plugin-tabs'
import mdItCustomAttrs from 'markdown-it-custom-attrs'
import alterUserBlock from './plugins/alterUserBlock'
import { pageViewPlugin } from './plugins/pageViewPlugin'
import { withMermaid } from 'vitepress-plugin-mermaid'

// https://vitepress.dev/reference/site-config
const config = defineVersionedConfig({
  // 检验文档中无效链接，暂时开启用于测试
  ignoreDeadLinks: true,
  title: "虚谷文档",
  description: "虚谷数据库文档中心",
  head: [
    ['link', { rel: 'icon', href: '/icon/favicon.ico' }],
    ["link", { rel: "stylesheet", href: "/fancybox/fancybox.css" },],
    ["script", { src: "/fancybox/fancybox.js" }],
  //  ["link", { rel: "stylesheet", href: "/style/railroad-diagrams.css" }],
    ["meta", { name: "keywords", content: "xugu, 虚谷, 虚谷文档" }],
    // 自定义统计脚本
    ['script', {}, `
      window.customAnalytics = {
        track: function(eventName, data) {
          const analytics = JSON.parse(localStorage.getItem('analytics') || '[]');
          analytics.push({
            type: 'event',
            eventName,
            data,
            timestamp: new Date().toISOString(),
            path: window.location.pathname,
            userAgent: navigator.userAgent
          });
          localStorage.setItem('analytics', JSON.stringify(analytics.slice(-1000)));
        }
      };
    `],
  ],
  cleanUrls: true,
  appearance: false,
  themeConfig: {
    // https://vitepress.dev/reference/default-theme-config
    versionSwitcher: false,
    search: {
      provider: 'local',
      options: {
        // Removes versioned and translated pages from search.
        _render(src, env, md) {
          if (env.frontmatter?.search === false) return "";
          if (env.relativePath.startsWith("translated/")) return "";
          if (env.relativePath.startsWith("versions/")) return "";
          return md.render(src, env);
        },
      },
    },
  },
  rewrites: {
    "versions/:version/translated/:lang/(.*)": ":lang/:version/(.*)",
    "translated/:lang/(.*)": ":lang/(.*)",
    "versions/:version/(.*)": ":version/(.*)",
    "analytics": "analytics",
  },
  versioning: {
    latestVersion: latest_version,
    rewrites: { localePrefix: "translated" },
    sidebars: {
      sidebarContentProcessor: processExistingEntries,
      sidebarUrlProcessor: (url: string, version: string) =>
        url.startsWith("/") ? `/${version}${url}` : url,
    },
  },
  locales: loadLocales(__dirname, ""),
  sitemap: {
    hostname: "https://docs.xugudb.com/",
    transformItems,
  },
  transformPageData,
  markdown: {
    breaks: true,  // 允许换行
    linkify: true,  // 自动识别链接
    config: (md) => {
      md.use(tabsMarkdownPlugin)
      md.use(alterUserBlock)
      md.use(mdItCustomAttrs, 'image', {
        'data-fancybox': "gallery"
      })
      
      // 注册页面访问量插件，并传递原始文本
      md.use(pageViewPlugin())
      
      // 添加 Mermaid 支持 - 暂时注释掉，使用其他方式
      // md.use(mermaid)
      
      // 确保env.source可用
      const originalRender = md.render
      md.render = function(src: string, env: any) {
        if (env && !env.source) {
          env.source = src
        }
        return originalRender.call(this, src, env)
      }
    },
    lineNumbers: true, //显示代码行数
    math: true//启用数学方程渲染
  },

  // 将 vite 配置放在根级别
  vite: {
    server: {
      host: '0.0.0.0', // 允许通过本地 IP 访问
      port: 8888, // 可以自定义端口
      allowedHosts: [ 'inside.xugudb.com', 'help.xugudb.com']
    }
  },
}, __dirname)

export default withMermaid(config as any)
